<?php


require_once("view/UserFileView.php");
require_once("Model/UserFileHandler.php");
	
class UserFileController{
	
	private $userFileHandler;
	private $userFileView;
	
	public function __construct(DBConnection $DBConnection, $DBPrefix){
		$this->userFileHandler = new UserFileHandler($DBConnection, $DBPrefix);
		$this->userFileView = new UserFileView();
		
	}
	
	public function DoControll($a_loggedInUserObject, $a_activeUserID, $a_userIdToRemove = false){
		$page = new Page();
		//Handle input
		//Did we pass a UserId that has been removed? if we did, remove all files
		if($a_userIdToRemove !== false){
			$this->userFileHandler->deleteAllFilesByUserId($a_userIdToRemove);
			return;
		}
		//Check if file was uploaded, if true, save it to disk
		if($this->userFileView->didUserUploadFile()){
			$result = $this->userFileHandler->saveFileToDisc($this->userFileView->GetFile(), $a_loggedInUserObject->userId);
			//Store upload message in session
			$_SESSION[NavigationView::FileUploadMessageCode] = $result;
			//Redirect to prevent double-trouble
			NavigationView::setHeadeLocation("index.php?" . NavigationView::controller . "=" . NavigationView::login);		
		}
		//Check if user tried to remove file, if true, remove it
		if($this->userFileView->didUserTryToRemoveFile()){
			$fileNameToRemove = $this->userFileView->getUserRemovedFileName();
			$fileToRemove = UserFile::create($a_loggedInUserObject->userId, $fileNameToRemove);
			
			$result = $this->userFileHandler->deleteUserFile($fileToRemove);
			$this->userFileView->generateRemoveFeedback($result);
		}
		
		//Handle Output
		if($a_activeUserID == $a_loggedInUserObject->userId){
			//We are looking at our own stuff
			$fileArray = $this->userFileHandler->getFilesByUserId($a_loggedInUserObject->userId);
			$page->body = $this->userFileView->generateOwnerOutput($fileArray);
			return $page;
		}
		//We are looking at someone elses stuff
		$fileArray = $this->userFileHandler->getFilesByUserId($a_activeUserID);
		$page->body = $this->userFileView->generateActiveUsersOutput($fileArray);
		return $page;
	}
}
